// pages/myfavor/myfavor.js
const app = getApp();
var funcs = require('../../static/js/func.js');
import {
  cities,
  areas
} from '../../static/js/city';


Page({

  /**
   * 页面的初始数据
   */
  data: {
    objectMultiArray: [cities, areas[0]],
    multiIndex: [0, 0],
    myfavorInst_infos: []
  },

  //city选择
  bindCityChange(event) {
    console.log('picker发送选择改变，携带值为', event.detail.value)
    let city_index = event.detail.value[0];
    let area_index = event.detail.value[1];
    let city = this.data.cities[city_index].name;
    let area = this.data.objectMultiArray[1][area_index].name;
    
    funcs.getInstDatabyName(city).then(res => {
      // console.log(res.data);
      let real_networkList = []
      let networkList = res.data.data;
      networkList.map((item, index) => {
        if (item.telephone != null && item.telephone.length > 0)
          real_networkList.push(item);
      })
      this.setData({
        networkList: real_networkList
      })
      this.getMyLocation(real_networkList)
    }).then(() => {
      this.setData({
        city: city,
        area: area,
        city_area: city + '-' + area
      })
      console.log(this.data.city)
      console.log(this.data.area)
      this.searchContext("")
    })
    // if(city!="全部"&&city!="成都市"){
    //   wx.showToast({
    //     title: "因数据安全考虑\r\n仅支持选择成都",
    //     icon: 'none',
    //     duration: 2000
    //   })
    //   return 
    // }
  },
  //city切换
  bindColumnCityChange(event) {
    console.log('修改的列为', event.detail.column, '，值为', event.detail.value);
    switch (event.detail.column) {
      case 0: //修改第一列
        let arr = this.data.multiIndex;
        arr[0] = event.detail.value;
        arr[1] = 0;
        this.setData({
          objectMultiArray: [cities, areas[event.detail.value]],
          multiIndex: arr,
        })
        break;
      case 1: //修改第二列
        let arr2 = this.data.multiIndex;
        arr2[1] = event.detail.value;
        // console.log(arr2)
        this.setData({
          multiIndex: arr2,
        })
        break;
    }
    // console.log(this.data.multiIndex)
  },
  junmToHome: function (res) {
    let data = res.currentTarget.dataset;
    console.log(data)
    var jsonString = JSON.stringify(data);
    //跳转页面并传递json字符串
    wx.navigateTo({
      url: '/pages/home/home?params=' + encodeURIComponent(jsonString)
    })
  },
  //area选择
  bindAreaChange(event) {
    let index = event.detail.value;
    let area = this.data.cities[index].name;
    this.setData({
      area: area
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this
    let _this = this
    console.log("监听onload")
    let openid = app.globalData.openid
    funcs.getFavorList(openid).then(res=>{
      if(res.data.succeed){
        that.getMyLocation(res.data.data.inslist).then(res=>{
          console.log(res)
          _this.setData({
            myfavorInst_infos:res
          })
        });
        // console.log(res.data.data)
      }
    })
  },
  jumptomap: function (res) {
    // console.log("here")
    // console.log(res.currentTarget.dataset)
    let data = res.currentTarget.dataset

    let longitude = data.longitude;
    let latitude = data.latitude;
    let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    let x = longitude - 0.0065;
    let y = latitude - 0.006;
    let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
    let wz = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
    let lon = z * Math.cos(wz);
    let lat = z * Math.sin(wz);
    longitude = lon;
    latitude = lat;
    console.log(latitude + latitude + data.nam + data.address)
    wx.openLocation({
      latitude: Number(latitude),
      longitude: Number(longitude),
      name: data.name,
      address: data.address
    })
  },
  call_phone: function (res) {
    let data = res.currentTarget.dataset
    wx.showModal({
      title: "提示",
      content: "拨打 " + data.telephone + " ?",
      complete: (res) => {
        if (res.cancel) {
          return
        }
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: data.telephone,
            success: function () {
              console.log("拨打电话成功！")
            },
            fail: function () {
              console.log("拨打电话失败！")
            }
          })
        }
      }
    })
  },
  onInput: function (e) {
    let onInput = e.detail.value
    console.log(e.detail.value)
    this.errorNotice()
    // this.searchContext(onInput)
    // this.searchContext2(onInput)
  },
  errorNotice: function (res) {
    wx.showToast({
      title: "因数据安全考虑\r\n目前暂不开放该功能",
      icon: 'none',
      duration: 2000
    })
  },
  getMyLocation: function (inputList) {
    return new Promise((resolve, reject) => {
      var _this = this;
      wx.getLocation({
        type: "gcj02",
        success(res) {
          const latitude = res.latitude;
          const longitude = res.longitude;
          app.globalData.latitude = latitude;
          app.globalData.longitude = longitude;
          let sortList = [];

          inputList.map((item, index) => {
            let distance = funcs.getDistance2(latitude, longitude, item.latitude, item.longitude);
            item.distance = distance;
            // if(item.address.search("成都市新都区大丰")!=-1)
            //   console.log("有成都")
            sortList.push(item);
          })
          //距离排序（最近优先）
          sortList.sort((item1, item2) => {
            return item1.distance - item2.distance
          })
          wx.hideLoading();

          if (_this.data.first_load == true && sortList.length !== 0) {
            let openid = app.globalData.openid
            funcs.judgeFavor(sortList[0].map_id,openid).then(res=>{
              console.log("res>",res)
              if(res.data.succeed){
                _this.setData({
                  liked: true
                })
              }else{
                _this.setData({
                  liked: false
                })
              }
              _this.setData({
                first_load: false,
                near_name: sortList[0].name,
                near_address: sortList[0].address,
                near_telephone: sortList[0].telephone,
                near_latitude: sortList[0].latitude,
                near_longitude: sortList[0].longitude,
                near_distance: sortList[0].distance,
                near_shophours: sortList[0].shophours,
                nearmapid:sortList[0].map_id,
              })
            })
          }
          _this.setData({
            maps_info: sortList,
            show_flag: sortList.length
          })
          resolve(sortList);
        }
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log("监听onShow")
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})